﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using unTroublemaker.Parsing;

namespace unTroublemaker
{
    public class Specification
    {
        private readonly bool _valid;

        public Specification(string file)
        {
            Name = "Unnamed specification";
            _valid = TryParse(file);
        }

        private bool TryParse(string file)
        {
            if (!File.Exists(file))
            {
                Error = "File does not exist: " + Path.GetFullPath(file);
                return false;
            }

            try
            {
                LoadDocument(XDocument.Load(file, LoadOptions.SetLineInfo));
                return true;
            }
            catch (IOException e)
            {
                Error = "Failed to access file: " + Path.GetFullPath(file) + "\r\n" + e.Format();
            }
            catch (Exception e)
            {
                Error = "Unhandled exception occured while parsing specification.\r\n" + e.Format();
            }

            return false;
        }

        private void LoadDocument(XDocument document)
        {
            if(document.Root == null)
                throw new Exception("Root node missing");

            var specParser = new SpecificationParser();
            Items = specParser.Parse(document.Root);

            var nameAttribute = (string)document.Root.Attribute("name");
            if (!string.IsNullOrEmpty(nameAttribute))
                Name = nameAttribute;
        }

        public bool Valid { get { return _valid; } }

        public string Error { get; set; }

        public ISpecificationItem[] Items { get; private set; }

        public string Name { get; set; }
    }
}